Skip to content

feat(csp): wire report-only CSP to a real reporting endpoint#263

Merged
kilbot merged 2 commits into
mainfrom
worktree-csp-reporting-endpoint
Jul 6, 2026
Merged

feat(csp): wire report-only CSP to a real reporting endpoint#263
kilbot merged 2 commits into
mainfrom
worktree-csp-reporting-endpoint

Conversation

@kilbot

@kilbot kilbot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Problem

The site was emitting this console error (twice — once per document, e.g. page + Stripe iframe) on every page load:

The Content Security Policy '…' was delivered in report-only mode, but does not specify a 'report-to'; the policy will have no effect.

The Content-Security-Policy-Report-Only header in next.config.ts had no report-to/report-uri directive and no collection endpoint anywhere in the app. A report-only policy never blocks (that's the point), so with nowhere to send reports it does nothing at all — the browser is correct that it "will have no effect." It's been inert this whole time, which also means the code comment's "verify clean against real traffic, then promote to enforcing" plan could never actually gather any data.

Fix (best-practice reporting wiring)

Rather than delete the header or blindly enforce an unvalidated policy, make the report-only phase actually work:

  • New POST /api/csp-report sink modeled on the existing report-failure route:
    • Accepts both wire formats: legacy application/csp-report (report-uri, used by Safari/Firefox) and the modern application/reports+json array (report-to, Reporting API, Chromium).
    • Rate-limited per IP (60/min, fail-open) + 8 KB body cap — it's an unauthenticated, browser-driven endpoint.
    • Sanitizes report fields (strips CR/LF/control chars, bounds length) before logging — log-injection guard.
    • Logs via infraLogger.warn → Loki/Sentry. Deliberately not the sale/Discord path: a CSP violation is diagnostic, not something to page anyone about.
    • Always returns 204 — a broken/abusive report must never surface to the visitor.
  • CSP directives: added report-uri /api/csp-report (legacy fallback) and report-to csp-endpoint (modern).
  • Reporting-Endpoints header: names the csp-endpoint group with the same-origin path, so it follows whichever host served the page (wcpos.com / www).

Once real violations have been observed clean, the header can be flipped from -Report-Only to enforcing.

Verification

  • 7 new unit tests (src/app/api/csp-report/route.test.ts): both formats, multi-violation arrays, non-CSP report filtering, log-injection sanitization, rate-limit drop, malformed JSON, oversized body. All green.
  • Full API-route suite: 240/240 passing.
  • ESLint + tsc --noEmit: clean on changed files.
  • Live dev-server check (next dev):
    • Response headers now include Reporting-Endpoints: csp-endpoint="/api/csp-report" and the CSP ends with …; report-uri /api/csp-report; report-to csp-endpoint.
    • POST /api/csp-report returns 204 for legacy, modern, and malformed bodies.
    • Server log confirmed both a legacy and a modern violation logged under wcpos·infra; malformed body logged nothing.

Notes

  • No behavior change for visitors — still report-only, still non-blocking.
  • Endpoint hardening mirrors the deferred follow-up noted for report-failure (abuse cap + no raw logging of attacker-controlled input).

Summary by CodeRabbit

  • New Features
    • Added a same-origin endpoint to receive Content Security Policy violation reports.
    • Support added for both legacy and modern CSP reporting formats.
  • Bug Fixes
    • Improved resilience against malformed payloads, oversized bodies, and unexpected report shapes (reports are safely ignored).
    • Enhanced sanitization to prevent unsafe or noisy content from reaching logs.
    • Requests beyond the rate limit are dropped without affecting the user experience.
  • Tests
    • Expanded automated coverage for size caps, batching limits, and sanitization behaviors.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kilbot has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai

coderabbitai Bot commented Jul 5, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 3 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 1e4046b9-e36f-4620-a6fe-beeaaf4a2a61

📥 Commits

Reviewing files that changed from the base of the PR and between db6356b and 82f8291.

📒 Files selected for processing (3)
  • next.config.ts
  • src/app/api/csp-report/route.test.ts
  • src/app/api/csp-report/route.ts
📝 Walkthrough

Walkthrough

This PR adds a same-origin CSP reporting endpoint at /api/csp-report. next.config.ts now routes report-only CSP violations to that path, and the new POST handler enforces size limits, rate limiting, payload normalization, sanitization, logging, and a 204 response. Tests cover the endpoint’s payload shapes and edge cases.

Changes

CSP Reporting

Layer / File(s) Summary
CSP header configuration
next.config.ts
Adds CSP_REPORT_PATH, report-uri/report-to directives on the report-only CSP, and a Reporting-Endpoints header mapping csp-endpoint to that path.
CSP report route implementation
src/app/api/csp-report/route.ts
Adds POST handling for request-size caps, IP rate limiting, legacy and Reporting API payload normalization, field sanitization, violation logging, and always returning 204.
Route test suite
src/app/api/csp-report/route.test.ts
Adds mocks for logger/rate-limiter and tests for legacy and modern payloads, URL and log-injection sanitization, batched-report limits, rate-limit fail-open, malformed JSON, unrecognized payloads, and size-cap enforcement.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: wiring report-only CSP to a real reporting endpoint.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-csp-reporting-endpoint

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/app/api/csp-report/route.test.ts (1)

120-129: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test only exercises the spoofable declared-length shortcut, not the real byte cap.

This test sends a small body with a large declared content-length header, which only proves the early declared-length check works. It doesn't cover the case of an actual oversized body without a (or with an honest small) content-length header, which is exactly the path that currently buffers the whole body via request.text() before checking size (see comment on route.ts). Consider adding a test that sends a real >8KB body to confirm the post-read cap actually works as intended.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/app/api/csp-report/route.test.ts` around lines 120 - 129, The current
csp-report test only covers the spoofable declared content-length shortcut, so
add coverage in the POST test suite for the real byte-size limit path in POST by
sending an actually oversized request body and verifying it is dropped after
read. Update the test around POST in csp-report/route.test.ts to use a payload
larger than the 8KB cap with an honest or absent content-length header, so it
exercises the request.text() buffering path and the post-read size check instead
of only the declared-length branch.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/app/api/csp-report/route.ts`:
- Around line 84-99: The POST handler in POST currently buffers the full request
body with request.text() before enforcing MAX_BODY_BYTES, so oversized payloads
can still consume memory. Update the body handling in
src/app/api/csp-report/route.ts to read the request as a stream, count bytes
incrementally, and abort immediately once the limit is exceeded; keep the
existing noContent behavior and preserve the limiter/clientIp/extractViolations
flow around the new streaming read.

---

Nitpick comments:
In `@src/app/api/csp-report/route.test.ts`:
- Around line 120-129: The current csp-report test only covers the spoofable
declared content-length shortcut, so add coverage in the POST test suite for the
real byte-size limit path in POST by sending an actually oversized request body
and verifying it is dropped after read. Update the test around POST in
csp-report/route.test.ts to use a payload larger than the 8KB cap with an honest
or absent content-length header, so it exercises the request.text() buffering
path and the post-read size check instead of only the declared-length branch.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 5f45c2b1-35ca-4b80-b75c-d19b70176380

📥 Commits

Reviewing files that changed from the base of the PR and between 2ef1925 and 2d6173c.

📒 Files selected for processing (3)
  • next.config.ts
  • src/app/api/csp-report/route.test.ts
  • src/app/api/csp-report/route.ts

Comment thread src/app/api/csp-report/route.ts
@github-actions

github-actions Bot commented Jul 5, 2026

Copy link
Copy Markdown

🚀 Preview: https://wcpos-5i1j801yu-wcpos.vercel.app

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2d6173cb23

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/app/api/csp-report/route.ts
Comment thread src/app/api/csp-report/route.ts Outdated
Comment thread src/app/api/csp-report/route.ts

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kilbot has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@wcpos-bot

wcpos-bot Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Post-fix triage for review feedback:

Thread File Issue Decision Commit
CodeRabbit inline route.ts Body cap was enforced after request.text() buffered the request Fixed with bounded stream read and oversized-stream regression test db6356b
Codex inline route.ts Reported URLs could log query/fragment secrets Fixed by stripping query strings and fragments from logged URL fields db6356b
Codex inline route.ts Duplicate body-cap-before-buffering concern Fixed by the same bounded stream reader db6356b
Codex inline route.ts Batched Reporting API payloads could emit too many warning logs Fixed by capping processed CSP violations per body db6356b
CodeRabbit review body route.test.ts Oversized-body coverage only used spoofed content-length Fixed with an actually oversized streamed-body test db6356b

Skipped threads:

Thread Reason for skipping
None All fresh unresolved actionable review feedback was fixed and resolved.

Validation:

  • pnpm install --frozen-lockfile passed.
  • pnpm exec vitest run src/app/api/csp-report/route.test.ts passed: 10 tests.
  • pnpm lint passed with existing warnings outside this change.
  • pnpm exec tsc --noEmit passed.
  • pnpm test:unit passed: 160 files, 1160 tests.
  • pnpm test:e2e --project=chromium could not complete in this container because Chromium cannot load libglib-2.0.so.0; pnpm exec playwright install-deps chromium also failed because the container cannot elevate via su.

Remaining unresolved inline review threads after resolving: 0.

kilbot and others added 2 commits July 6, 2026 16:14
The Content-Security-Policy-Report-Only header had no report-to/report-uri
directive, so browsers warned it 'will have no effect' — a report-only policy
with nowhere to send reports neither blocks nor reports, making it inert (and
noisy in the console).

Add the reporting plumbing so the header does its job:
- New POST /api/csp-report sink that accepts both wire formats (legacy
  application/csp-report and the Reporting API's application/reports+json),
  rate-limited + size-capped + always 204, logging via infraLogger (Loki/
  Sentry, not the Discord sale path).
- report-uri + report-to directives on the CSP, plus a Reporting-Endpoints
  header naming the csp-endpoint group.

This finally makes the 'verify clean, then enforce' plan actionable: real
violations now land in the log sink instead of being silently discarded.
@kilbot kilbot force-pushed the worktree-csp-reporting-endpoint branch from db6356b to 82f8291 Compare July 6, 2026 14:15

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kilbot has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@kilbot

kilbot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

/fix triage — merge-readiness pass

# Source Finding Class Decision Outcome
1 CodeRabbit (Major) + Codex (P2) request.text() buffered the full body before the MAX_BODY_BYTES cap ran Logic Fix Already fixed in prior commit — replaced with readBodyUnderLimit() streaming reader that cancels once 8 KB is exceeded (before buffering); regression test stops reading an actually oversized streamed body after the byte cap. Thread resolved.
2 Codex (P2) Reported document-uri/blocked-uri query strings could leak reset tokens/emails (/reset-password?token=…) into infra logs Logic Fix Already fixed — sanitizeUrlField() drops search+hash before logging; test strips query strings and fragments from reported URLs. Thread resolved.
3 Codex (P2) A batched Reporting-API POST could emit hundreds of warn logs on one rate-limited request Logic Fix Already fixed — MAX_VIOLATIONS_PER_REPORT = 10 cap via .slice(); test caps logged violations from a modern batched report. Thread resolved.
4 CodeRabbit (Nitpick) Body-cap test only exercised the spoofable declared-content-length shortcut, not the real byte cap Mechanical Fix Covered by the streaming oversized-body test added for #1.
5 CI E2E Tests failed — license-flows.spec.ts:281 strict-mode "2 elements" on the expired-license downloads row Logic Fix Not caused by this PR. The branch was based on pre-#270 main; the failing spec + downloads component predate the account-renew work. Rebased onto current origin/main (clean, no conflicts). The spec and all downloads/release components are now byte-identical to main, which passes E2E. This PR now differs from main by exactly the 3 CSP files.

Verification (post-rebase)

  • CSP unit tests: 10/10 passing
  • ESLint + tsc --noEmit: clean on changed files
  • git diff --name-only origin/main..HEAD → only next.config.ts, src/app/api/csp-report/route.ts, route.test.ts
  • CSP reporting directives + Reporting-Endpoints header confirmed intact after rebase

All 4 review threads resolved; the only blocker (E2E) was a stale-base artifact now cleared. Re-running CI to confirm green.

@kilbot

kilbot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

✅ CI is green after the rebase — Test, E2E Tests, and both CodeQL analyses all pass. The earlier E2E failure (license-flows.spec.ts:281) was confirmed to be a stale-base artifact, not caused by this PR: the spec and downloads components are byte-identical to main, and the branch now differs from main by only the 3 CSP files. All review threads resolved. Merge-ready pending your review.

@github-actions

github-actions Bot commented Jul 6, 2026

Copy link
Copy Markdown

🚀 Preview: https://wcpos-5jkukj16n-wcpos.vercel.app

@kilbot kilbot merged commit 04cd48f into main Jul 6, 2026
9 checks passed
@kilbot kilbot deleted the worktree-csp-reporting-endpoint branch July 6, 2026 14:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant